package swing.chapter03;

import swing.util.SwingConsle;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * 组合框 （下拉列表）
 */
public class ComboBoxes extends JFrame {
    private String [] language = {"Java", "C++", "Python", "R", "Go", "Javascript", "Html", "Jsp", "PHP"};
    private JTextField t = new JTextField(15);
    private JComboBox c = new JComboBox();
    private JButton b = new JButton("Add Items");
    private int count = 0;

    public ComboBoxes(){
        for(int i=0;i<4;i++){
            c.addItem(language[count++]);
        }

        t.setEditable(false);
        b.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if(count < language.length){
                    c.addItem(language[count++]);
                }
            }
        });

        c.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                t.setText("Index: " + c.getSelectedIndex() + " " + ((JComboBox)e.getSource()).getSelectedItem());
            }
        });

        setLayout(new FlowLayout());
        add(t);
        add(c);
        add(b);
    }

    public static void main(String[] args) {
        SwingConsle.run(new ComboBoxes(), 200, 175);
    }
}
